//
//  DCIMFriendListViewController.m
//  xmppBase
//
//  Created by striby on 16/1/7.
//  Copyright © 2016年 com.dc. All rights reserved.
//

#import "DCIMFriendListViewController.h"
#import "DTLetterButton.h"
#import "XMPPUser.h"

@interface DCIMFriendListViewController ()
{
    NSMutableDictionary * _myFriends;
    
    DTLetterButton * preBtn;
    
    /**
     *  选中的用户集合
     */
    NSMutableSet * _selectedUsers;
    
    UIView* A_Z_selectionView;
}

@property(nonatomic,strong)DCIMGroupManager * groupManager;

@property(nonatomic,strong)XMPPRoom * room;
@end

@implementation DCIMFriendListViewController

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _keys = @[@"#",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    _selectedUsers = [[NSMutableSet alloc]init];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DCDeviceWidth, DCDeviceHeight)];
    self.tableView.delegate=self;
    self.tableView.dataSource =self;

//    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self.view addSubview:self.tableView];
    
    [self creatA_Z_View];
    
    [self loadUsers];
    
    [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, TabBarHeight, 0)];
    
    [self.tableView setShowsVerticalScrollIndicator:NO];
    
    switch (self.friendListType) {
        case DCFriendListTypeInviteFriends:
        case DCFriendListTypeDiscussion:
        {
            UIBarButtonItem * item = [[UIBarButtonItem alloc]initWithTitle:@"确认" style:UIBarButtonItemStylePlain target:self action:@selector(commit)];
            
            self.navigationItem.rightBarButtonItem=item;
        }
            break;
            
            
        default:
            break;
    }
    
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(A__ZselectionMovedIn:) name:TOUCH_MOVED_IN_LETTER_BUTTON object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadUsers) name:kFriendShipStatusChanged object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(createdGroupSuccessed) name:kDidCreatedGroupSuccessed object:nil];
    [[NSNotificationCenter defaultCenter ]addObserver:self selector:@selector(loadUsers) name:kXmppUserInfoGetSuccessed object:nil];
}



#pragma mark - load data
-(void)loadUsers
{
    
    
    /**
     *  获取好友
     */

     __block NSArray * arr = [[DCXMPPTool shareInstance].xmppRosterMemoryStorage unsortedUsers];
    
    if (self) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            
            _allKeys = [NSMutableArray new];
            _myFriends = [NSMutableDictionary new];
           id result  = [self sortedArrayWithPinYinDic:arr];
            dispatch_async(dispatch_get_main_queue(), ^{
                _myFriends = result;
                [self.tableView reloadData];
                
            });
        });
    }
    
}

#pragma mark - 创建群组成功
-(void)createdGroupSuccessed
{

    for (XMPPUserMemoryStorageObject * user in _selectedUsers  ) {
        
        [_room inviteUser:user.jid withMessage:@""];
    }
   
}

#pragma mark - 提交操作
-(void)commit
{
    switch (self.friendListType) {
        case DCFriendListTypeNormal:
        {
        
        }
            break;
            
        case DCFriendListTypeDiscussion:
        {
            if(!_selectedUsers)
            {
                return;
            }
            
            if (_selectedUsers.count<1) {
                return;
            }
            
            _groupManager = [DCIMGroupManager shareInstance];
            
            
            NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
            [formatter setDateFormat:@"yyyy-MM-dd/HH:mm:ss"];
            
          
            
            DCXMPPTool * xmppTool = [DCXMPPTool shareInstance];
            
            XMPPJID * jid =[XMPPJID jidWithUser:xmppTool.xmppStream.generateUUID domain:[NSString stringWithFormat:@"%@.%@",GroupDomainFirstName,DomainName] resource:isIPHONE?iPadResourceName:iPadResourceName];
            
            _room = [_groupManager createRoomWithRoomJid:jid];
            
            
            XMPPvCardTemp * card = [xmppTool.xmppvCardTempModule vCardTempForJID:xmppTool.xmppStream.myJID shouldFetch:YES];
            
            [_room joinRoomUsingNickname:card.nickname history:nil];
            

            DCIMConversationViewController * vc = [[DCIMConversationViewController alloc]init];
            
            vc.targetJID = jid;
            
            vc.conversationType = DCConversationTypeGroup;
            
            [self.navigationController pushViewController:vc animated:YES];

        }
            break;
            
        case DCFriendListTypeInviteFriends:
        {
            
            if(!_selectedUsers)
            {
                return;
            }
            
            if (_selectedUsers.count<1) {
                return;
            }
            
            XMPPRoom * room = self.extraInfo;
            
            for (XMPPUserMemoryStorageObject * user in _selectedUsers  ) {
                
                [room inviteUser:user.jid withMessage:@""];
            }
            
            
            
            [self.navigationController setViewControllers:@[self.navigationController.viewControllers[0] ]];
        }
            break;
            
        case DCFriendListTypePrivateChat:
        {
            
        }
            break;
            
        case DCFriendListTypeChatWithSomeoneInDiscussion:
        {
            
        }
            break;
            
        default:
            break;
    }
}


#pragma mark  - A_Z 选择
-(void)creatA_Z_View
{
    
    
    A_Z_selectionView = [[UIView alloc]initWithFrame:CGRectZero];
    
    for (int i =0; i<_keys.count; i++) {
        DTLetterButton * view = [[DTLetterButton alloc]initWithFrame:CGRectMake(0, cSize*i, cSize, cSize)];
        view.tag=i;
        [view setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [view setTitle:_keys[i] forState:UIControlStateNormal];
        
        view.titleLabel.font = [UIFont systemFontOfSize:12];
        [view addTarget:self action:@selector(A__Zselecion:) forControlEvents:UIControlEventTouchDown];
        
        [A_Z_selectionView addSubview:view];
        
        if (i==_keys.count-1) {
            [A_Z_selectionView setFrame:CGRectMake(self.tableView.frame.size.width-cSize,( self.tableView.frame.size.height-_keys.count*cSize)/2, cSize, _keys.count*cSize)];
        }
    }
    
    [self.view addSubview:A_Z_selectionView];
    
}

-(void)A__Zselecion:(UIButton*)sender
{
    
    
    NSInteger index = sender.tag;
    
    DTLetterButton * selectedBtn =(DTLetterButton*)[A_Z_selectionView viewWithTag:index];;
    
    if (selectedBtn!=preBtn) {
        preBtn = selectedBtn;
        
        [self selectBtnAtIndex:index];
    }
    
    
    
    
}

-(void)A__ZselectionMovedIn:(NSNotification*)sender
{
    
    
    NSDictionary * obj = sender.object;
    
    double y = [obj[@"y"] doubleValue];
    
    int index = y/cSize;
    
    if (index>=0&&index<_keys.count) {
        DTLetterButton * selectedBtn =(DTLetterButton*)[A_Z_selectionView viewWithTag:index];;
        
        if (selectedBtn!=preBtn) {
            preBtn = selectedBtn;
            
            [self selectBtnAtIndex:index];
        }
    }
    
    
}

-(void)selectBtnAtIndex:(NSInteger)index
{
    DLog(@"%@",_keys[index]);
    
    NSString * key =_keys[index];
    
    for (int i = 0 ;i<_allKeys.count;i++) {
        NSString * str = _allKeys[i];
        if ([str isEqualToString:key]) {
            
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:i];
            
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
            break;
        }
    }
    
}

#pragma mark -   拼音操作

/**
 *  汉字转拼音
 *
 *  @param hanZi 汉字
 *
 *  @return 转换后的拼音
 */
-(NSString *) hanZiToPinYinWithString:(NSString *)hanZi
{
    if(!hanZi) return nil;
    NSString *pinYinResult=[NSString string];
    for(int j=0;j<hanZi.length;j++){
        NSString *singlePinyinLetter=[[NSString stringWithFormat:@"%c",pinyinFirstLetter([hanZi characterAtIndex:j])] uppercaseString];
        pinYinResult=[pinYinResult stringByAppendingString:singlePinyinLetter];
        
    }
    
    return pinYinResult;
    
}


/**
 *  根据转换拼音后的字典排序
 *
 *  @param pinyinDic 转换后的字典
 *
 *  @return 对应排序的字典
 */
-(NSMutableDictionary *) sortedArrayWithPinYinDic:(NSArray *) friends
{
    if(!friends) return nil;
    
    NSMutableDictionary *returnDic = [NSMutableDictionary new];
    _tempOtherArr = [NSMutableArray new];
    BOOL isReturn = NO;
    
    for (NSString *key in _keys) {
        
        if ([_tempOtherArr count]) {
            isReturn = YES;
        }
        
        NSMutableArray *tempArr = [NSMutableArray new];
        for (XMPPUserMemoryStorageObject *user in friends) {
            
            XMPPvCardTemp * card = [[DCXMPPTool shareInstance].xmppvCardTempModule vCardTempForJID:user.jid shouldFetch:YES];
            
            //无昵称 过滤
            if (card.nickname==nil) {
                continue;
            }
            
            NSString *pyResult = [self hanZiToPinYinWithString:card.nickname];

            
            NSString *firstLetter = [pyResult substringToIndex:1];
            if ([firstLetter isEqualToString:key]){
                [tempArr addObject:user];
            }
            
            if(isReturn) continue;
            char c = [pyResult characterAtIndex:0];
            if (isalpha(c) == 0) {
                [_tempOtherArr addObject:user];
            }
        }
        if(![tempArr count]) continue;
        [returnDic setObject:tempArr forKey:key];
        
    }
    if([_tempOtherArr count])
        [returnDic setObject:_tempOtherArr forKey:@"#"];
    
    
    _allKeys = [[returnDic allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    return returnDic;
}


#pragma mark  -  选择代理
-(void)friendCellSelectEventWithIndexPath:(NSIndexPath *)indexPath isSelected:(BOOL)isSelected
{
    NSString *key = [_allKeys objectAtIndex:indexPath.section];
    NSArray *arrayForKey = [_myFriends objectForKey:key];
    
    
    XMPPUserMemoryStorageObject * user = arrayForKey[indexPath.row];

    
    if (isSelected) {
        [_selectedUsers addObject:user];
    }
    else
    {
        [_selectedUsers removeObject:user];
    }
}


#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (self.friendListType==DCFriendListTypeDiscussion||self.friendListType==DCFriendListTypeInviteFriends) {
        DCMyFriendTableViewCell * cell = (DCMyFriendTableViewCell*)[tableView cellForRowAtIndexPath:indexPath];
        
        [cell SelectBtnPressed:nil];
        
        return;
    }
    else if (self.friendListType==DCFriendListTypePrivateChat)
    {
        
        NSString *key = [_allKeys objectAtIndex:indexPath.section];
        NSArray *arrayForKey = [_myFriends objectForKey:key];
        
        XMPPUserMemoryStorageObject * user = arrayForKey[indexPath.row];
        
        DCIMConversationViewController * vc = [[DCIMConversationViewController alloc]init];
        
        vc.targetJID = user.jid;
        
        vc.conversationType = DCConversationTypePrivate;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
    else
    {
        NSString *key = [_allKeys objectAtIndex:indexPath.section];
        NSArray *arrayForKey = [_myFriends objectForKey:key];
        
        XMPPUserMemoryStorageObject * user = arrayForKey[indexPath.row];
        
        DCIMUserInfoViewController * vc = [[DCIMUserInfoViewController alloc]init];
        vc.userJid = user.jid;
        [self.navigationController pushViewController:vc animated:YES];

    }
    
    
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    
    if (_allKeys.count==0) {
        return 0;
    }
    
    NSString *key = [_allKeys objectAtIndex:section];
    
    NSArray *arr = [_myFriends objectForKey:key];
    
    return [arr count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _allKeys.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (_allKeys.count>section) {
        NSString *key = [_allKeys objectAtIndex:section];
        return key;
    }
    else
    {
        return @"";
    }
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DCMyFriendTableViewCell *cell = [[[NSBundle mainBundle]loadNibNamed:@"DCMyFriendTableViewCell" owner:nil options:nil]lastObject];
    cell.indexPath = indexPath;
    cell.delegate=self;
    if (self.friendListType==DCFriendListTypeDiscussion||self.friendListType==DCFriendListTypeInviteFriends) {
        [cell setHidenSelectStatusBtn:NO];
    }
    else
    {
        [cell setHidenSelectStatusBtn:YES];
    }
    
    
    NSString *key = [_allKeys objectAtIndex:indexPath.section];
    NSArray *arrayForKey = [_myFriends objectForKey:key];
    
     XMPPUserMemoryStorageObject * user = arrayForKey[indexPath.row];

    
    XMPPvCardTemp * card = [[DCXMPPTool shareInstance].xmppvCardTempModule vCardTempForJID:user.jid shouldFetch:YES];
    

    if (card.photo) {
        cell.UserIcon.image = [UIImage imageWithData:card.photo];
    }
    else
    {
        [cell.UserIcon setImage:[UIImage imageNamed:@"defaultUserIcon"]];
    }
    

 
        cell.UserName.text = card.nickname;
  
    
    
    if ([_selectedUsers containsObject:user]) {
        cell.isBtnSelected=YES;
    }
    else
    {
        cell.isBtnSelected = NO;
    }
    
    [cell ChangeCurrentBtnImage];
    
    return cell;
}




@end
